package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.stark.nettool.lib.NetToolBox;
import com.stark.nettool.lib.TraceRouteInfo;
import com.stark.nettool.lib.TraceRouter;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.IpScanAdapter;
import flc.ast.adapter.RecordAdapter;
import flc.ast.adapter.TraceRouteAdapter;
import flc.ast.databinding.ActivityIpScanBinding;
import stark.common.basic.event.EventStatProxy;

public class IpScanActivity extends BaseAc<ActivityIpScanBinding> {

    private String ip;

    @Override
    protected int onCreate() {
        return R.layout.activity_ip_scan;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivIpScanBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvStart.setOnClickListener(this);
        mDataBinding.tvClear.setOnClickListener(this);
        mDataBinding.ivIpClear.setOnClickListener(this);

        mDataBinding.rvIpScan.setLayoutManager(new LinearLayoutManager(mContext));
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvStart://开始
                ip = mDataBinding.etIp.getText().toString();
                if (TextUtils.isEmpty(ip)) {
                    mDataBinding.etIp.requestFocus();
                    ToastUtils.showShort(getString(R.string.please_input_ip));
                    return;
                }
                startTrace();
                break;
            case R.id.ivIpClear://ip清空
                mDataBinding.etIp.setText("");
                break;
            case R.id.tvClear://清空
                mDataBinding.etIp.setText("");
                mDataBinding.rvIpScan.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void startTrace() {

        showDialog(getString(R.string.query_ing));
        IpScanAdapter ipScanAdapter = new IpScanAdapter();
        mDataBinding.rvIpScan.setAdapter(ipScanAdapter);
        int ttl = 1;
        int maxTtl = 40;
        NetToolBox.traceRoute(ttl, maxTtl, ip, new TraceRouter.IListener() {
            @Override
            public void onGetRoute(TraceRouteInfo container) {
                mDataBinding.rvIpScan.setVisibility(View.VISIBLE);
                ipScanAdapter.addData(container);
            }

            @Override
            public void onTimeOut() {
                dismissDialog();
            }

            @Override
            public void onFinish() {
                dismissDialog();
            }
        });
    }

}